package com.fary.converters;

import com.fary.po.Man;
import com.fary.po.Person;
import com.fary.po.Woman;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

public class MyConverterFactory implements ConverterFactory<String, Person> {

    @Override
    public <T extends Person> Converter<String, T> getConverter(Class<T> targetType) {
        System.out.println("targetType:" + targetType);
        return new StringToPerson<>(targetType);
    }

    private static final class StringToPerson<T extends Person> implements Converter<String, T> {

        private final Class<T> targetType;

        public StringToPerson(Class<T> targetType) {
            this.targetType = targetType;
        }

        @Override
        public T convert(String source) {
            String[] split = source.split("-");
            if (Man.class == targetType) {
                return (T) new Man(split[0], Integer.parseInt(split[1]));
            } else if (Woman.class == targetType) {
                return (T) new Woman(split[0], Integer.parseInt(split[1]));
            }
            return null;
        }
    }
}
